package com.xiaoq.manager.endpoint;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.sites.IMerchantApi;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.apis.sites.SitesInfo4SocialVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.manager.entity.MerchantFunEntity;
import com.xiaoq.manager.entity.MerchantFunInner;
import com.xiaoq.manager.entity.MerchantMgrEntity;
import com.xiaoq.manager.entity.MerchantRoleEntity;
import com.xiaoq.manager.repository.IMerchantMgrRepository;
import com.xiaoq.manager.service.IManagerAccountService;
import com.xiaoq.manager.service.IMerchantFunService;
import com.xiaoq.manager.service.IMerchantRoleService;
import com.xiaoq.manager.vo.MailVo;
import com.xiaoq.manager.vo.Manager4Info;
import com.xiaoq.manager.vo.Manager4Password;
import com.xiaoq.manager.vo.ManagerAccountVo;
import com.xiaoq.manager.vo.ManagerAdditionVo;
import com.xiaoq.manager.vo.ManagerUpdateVo;
import com.xiaoq.manager.vo.ManagerUpdationVo;
import com.xiaoq.manager.vo.ManagerVo;
import com.xiaoq.manager.vo.MerchantRoleVo;
import com.xiaoq.oauth2.entity.OAuth2TokenEntity;
import com.xiaoq.oauth2.service.OAuth2Service;
import com.xiaoq.push.service.PushMessageService;
import com.xiaoq.user.endpoint.LoginVo;
import com.xiaoq.users.redis.RedisTemplate4JedisCluster;
import com.xiaoq.users.service.VerificationCodeService;
import com.xiaoq.users.service.exception.AuthenFailException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ResponseHeader;

@RestController
@RequestMapping(value = "/api/v1/manager")
@Api(tags={"管理员相关Api"})
public class ManagerAccountEndpoint {
	
	@Autowired
	private OAuth2Service oAuth2Service;
	
	@Autowired
	private IdGenerator idGenerator;
	
	@Autowired
	private IManagerAccountService managerAccountSer;
	
	@Autowired
	private IMerchantMgrRepository merchantMgrRep;
	
	@Autowired
    PushMessageService pushMessageService;
	
	@Autowired
	private IMerchantFunService merchantFunSer;
	
	@Autowired
	private IMerchantRoleService merchantRoleSer;
	
	@Reference(interfaceClass=IMerchantApi.class,check=false,version="1.0.0")
	private IMerchantApi merchantDubboApi;
	
	@Reference(interfaceClass=ISitesApi.class,check=false,version="1.0.0")
	private ISitesApi sitesApi;
	
	@Autowired
	private VerificationCodeService verificationCodeService;
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;
	
	private class ManagerDataResponse extends GenericDataResponse<ManagerVo>{}
	
	
	private class ManagerAccountDataResponse extends GenericDataResponse<ManagerAccountVo> {}
	
	private class MerchantRoleListResponse extends GenericListResponse<MerchantRoleVo> {}
	
	private class MerchantRoleDataResonse extends GenericDataResponse<MerchantRoleVo> {}
	
	private class Manager4InfoListResponse extends GenericListResponse<Manager4Info> {}
	
	private class ManagerBackViewDataResponse extends GenericDataResponse<ManagerAdditionVo> {}
	
	private class ManagerFunListResponse extends GenericListResponse<MerchantFunEntity> {}
	
	private static final Logger LOG = LoggerFactory.getLogger(ManagerAccountEndpoint.class);
	
	@ApiOperation(value = "角色名称是否重复", notes = "角色名称是否重复")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "角色名称是否重复") })
	@PostMapping(value = "/roleName", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findRoleByName(
			@RequestParam(value="roleName",required=true)@ApiParam(value="角色名称",required=true)String roleName,
			HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		boolean result = merchantRoleSer.findMerchantRoleByRoleName(roleName,shopId);
		if(result){
			return GenericDataResponse.okWithData("1");
		}else{
			return GenericDataResponse.okWithData("0");
		}
		
		
	}
	
	@ApiOperation(value = "重置密码", notes = "重置密码")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "重置密码") })
	@PostMapping(value = "/mobile/passwd", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> changePasswdByPhone(@RequestBody Manager4Password manager4Password){
		String mobile = manager4Password.getMobile();
		String password = manager4Password.getPasswd();
		String smsCode = manager4Password.getSmsCode();
		if (StringUtils.isAnyBlank(mobile, password,smsCode)) {
			return GenericResponse.ng("手机号、密码、验证码都不能为空");
		}
		boolean isVerified = verificationCodeService.verifyVerificationCode(mobile, smsCode);
		if (!isVerified) {
			return GenericResponse.ng("短信验证码不正确或已超时");
		}
		
		try {
			managerAccountSer.resetPassword(mobile, password);
		} catch (Exception e) {
			return GenericResponse.ng(e.getMessage());
		}
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "获取功能列表", notes = "获取功能列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ManagerFunListResponse.class, message = "获取功能列表") })
	@GetMapping(value = "/funList", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getMerchantFunList(@RequestParam(value="type",required=false)@ApiParam(value="00政府，10景区",required=false)String type,HttpServletRequest request) {

		if(StringUtils.isNotBlank(type)&&"00".equals(type)){
			MerchantRoleEntity merchantRole = merchantRoleSer.findById("superManager002");
			List<MerchantFunInner> merchantFunLists = merchantRole.getRoleList();
			return ManagerFunListResponse.listNoCount(merchantFunLists);

		}else{
			List<MerchantFunEntity> merchantFunList = merchantFunSer.findMerchantFunList();
			return ManagerFunListResponse.listNoCount(merchantFunList);
		}


		
	}

	@ApiOperation(value = "员工的停用和启用", notes = "员工的停用和启用")
	@ApiResponses({ @ApiResponse(code = 200, response = ManagerBackViewDataResponse.class, message = "员工的停用和启用") })
	@PutMapping(value = "/status", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateManagerStatus(
			@RequestParam(value="managerId",required=true)@ApiParam(value="编辑的管理员Id",required=true)String managerId,
			@RequestParam(value="status",required=true)@ApiParam(value="传相反的状态修改",required=true)int status,
			HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		MerchantMgrEntity merchantInDB = managerAccountSer.findById(userId);
		if(isSuperManager(merchantInDB)){
			merchantMgrRep.updateMerchantMgrStatus(managerId, status);
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("您不是超级管理员没有权限！");
		}
		
	}
	@ApiOperation(value = "管理员编辑回显", notes = "管理员编辑回显")
	@ApiResponses({ @ApiResponse(code = 200, response = ManagerBackViewDataResponse.class, message = "管理员编辑回显") })
	@GetMapping(value = "/backView", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> managerView(@RequestParam(value="managerId",required=true)@ApiParam(value="编辑的管理员Id",required=true)String managerId,HttpServletRequest request) {
		String superManagerId = (String) request.getAttribute("userId");
		MerchantMgrEntity merchantInDB = managerAccountSer.findById(superManagerId);
		if(isSuperManager(merchantInDB)){
			MerchantMgrEntity merchantMgr = managerAccountSer.findById(managerId);
			ManagerAdditionVo managerVo = new ManagerAdditionVo();
			if(merchantMgr!=null){
				BeanUtils.copyProperties(merchantMgr, managerVo);
			}
			managerVo.setPasswd(null);
			return ManagerDataResponse.okWithData(managerVo);
		}else{
			return GenericResponse.ng("您不是超级管理员没有权限！");
		}
		
	}
	@ApiOperation(value = "修改员工", notes = "修改员工")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "修改员工") })
	@PutMapping(value = "/man_mgr", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateManager(
			@RequestBody ManagerUpdationVo managerUpdationVo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		MerchantMgrEntity merchantInDB = managerAccountSer.findById(userId);
		if(isSuperManager(merchantInDB)){
			MerchantMgrEntity merchant = new MerchantMgrEntity();
			BeanUtils.copyProperties(managerUpdationVo, merchant);
			
			boolean result = false;
			try {
				result = managerAccountSer.updataMerchant(merchant);
			} catch (Exception e) {
				return GenericResponse.ng(e.getMessage());
			}
			if(result){
				return GenericResponse.ok();
			}else{
				return GenericResponse.ng("编辑失败！");
			}
		}else{
			return GenericResponse.ng("您不是超级管理员没有权限！");
		}
		
	}

	@ApiOperation(value = "修改账号(对政府)", notes = "修改账号(对政府)")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "修改账号(对政府)") })
	@PutMapping(value = "/man_mgr4gov", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateManager4Gov(
			@RequestBody ManagerVo managerVo,HttpServletRequest request) {

		String userId = (String) request.getAttribute("userId");
		MerchantMgrEntity merchantInDB = managerAccountSer.findById(userId);
		if(StringUtils.isNotBlank(managerVo.getName())){
			merchantInDB.setName(managerVo.getName());
		}
		if(StringUtils.isNotBlank(managerVo.getAddress())){
			merchantInDB.setAddress(managerVo.getAddress());
		}

		if(StringUtils.isNotBlank(managerVo.getLogoUrl())){
			merchantInDB.setLogoUrl(managerVo.getLogoUrl());
		}
		managerAccountSer.save(merchantInDB);
		return GenericResponse.ok();

	}

	@ApiOperation(value = "删除一个管理员(非超级管理员)", notes = "删除一个管理员")
	@ApiResponses({ @ApiResponse(code = 200, message = "删除一个管理员", response = Manager4InfoListResponse.class)})
	@DeleteMapping(value = "/managers", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> delManager(@RequestParam(value="managerId",required=true)@ApiParam(value="编辑的管理员Id",required=true)String managerId,HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		MerchantMgrEntity merchantInDB = managerAccountSer.findById(userId);
		if(isSuperManager(merchantInDB)){
			merchantMgrRep.delMerchantMgr(managerId);
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("您不是超级管理员没有权限！");
		}
		
		
	}
	
	@ApiOperation(value = "员工管理列表", notes = "员工管理列表")
	@ApiResponses({ @ApiResponse(code = 200, message = "员工管理列表", response = Manager4InfoListResponse.class)})
	@GetMapping(value = "/managers", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> managerList(HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<MerchantMgrEntity> merchantMgrList = merchantMgrRep.findByShopId(shopId);
		Manager4Info manager4Info = null;
		List<Manager4Info> manager4InfoList = new ArrayList<>();
		for(MerchantMgrEntity merchantMgr:merchantMgrList){
			manager4Info = new Manager4Info();
			BeanUtils.copyProperties(merchantMgr, manager4Info);
			String roleId = merchantMgr.getRoleId();
			MerchantRoleEntity merchantRole = merchantRoleSer.findById(roleId);
			if(merchantRole!=null){
				manager4Info.setRoleName(merchantRole.getName());
				manager4Info.setRoleCode(merchantRole.getCode());
			}
			
			manager4InfoList.add(manager4Info);
		}
		return Manager4InfoListResponse.listNoCount(manager4InfoList);
		
	}
	@ApiOperation(value = "根据角色Id获取员工列表", notes = "根据角色Id获取员工列表")
	@ApiResponses({ @ApiResponse(code = 200, message = "根据角色Id获取员工列表", response = Manager4InfoListResponse.class)})
	@GetMapping(value = "/managers4role", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> findManagersByRole(
			@RequestParam(value="roleId",required=true)@ApiParam(value="角色列表",required=true)String roleId,
			HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<MerchantMgrEntity> merchantMgrList = merchantMgrRep.findByRoleId(roleId,shopId);
		Manager4Info manager4Info = null;
		List<Manager4Info> manager4InfoList = new ArrayList<>();
		for(MerchantMgrEntity merchantMgr:merchantMgrList){
			manager4Info = new Manager4Info();
			BeanUtils.copyProperties(merchantMgr, manager4Info);
			String roleIds = merchantMgr.getRoleId();
			MerchantRoleEntity merchantRole = merchantRoleSer.findById(roleIds);
			if(merchantRole!=null){
				manager4Info.setRoleName(merchantRole.getName());
				manager4Info.setRoleCode(merchantRole.getCode());
			}
			
			manager4InfoList.add(manager4Info);
		}
		return Manager4InfoListResponse.listNoCount(manager4InfoList);
		
	}
	
	@ApiOperation(value = "确定是指定管理员手机号(解绑管理员手机号第一步)", notes = "确定是指定管理员手机号")
	@ApiResponses({ @ApiResponse(code = 200, message = "确定是指定管理员手机号", response = GenericResponse.class)})
	@GetMapping(value = "/manager/mobile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> confirmManager(
			@RequestParam(value="mobile",required=true)@ApiParam(value="电话号码",required=true)String mobile,
			@RequestParam(value="smsCode",required=true)@ApiParam(value="短信验证码",required=true)String smsCode,
			HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		
		if (StringUtils.isAnyBlank(mobile,smsCode)) {
			return GenericResponse.ng("手机号、短信验证码都不能为空");
		}
		
		boolean isVerified = verificationCodeService.verifyVerificationCode(mobile, smsCode);
		if (!isVerified) {
			return GenericResponse.ng("短信验证码不正确或已超时");
		}
		
		MerchantMgrEntity merchantMgr = managerAccountSer.findById(userId);
		if(!mobile.equals(merchantMgr.getMobile())){
			return GenericResponse.ng("不是超级管理账号！");
		}
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "解绑管理员手机号第二步", notes = "解绑管理员手机号第二步")
	@ApiResponses({ @ApiResponse(code = 200, message = "解绑管理员手机号第二步", response = GenericResponse.class)})
	@GetMapping(value = "/unTyMobile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<?> unTyMobile(
			@RequestParam(value="oldMobile",required=true)@ApiParam(value="旧的电话号码",required=true)String oldMobile,
			@RequestParam(value="oldSmsCode",required=true)@ApiParam(value="旧的短信验证码",required=true)String oldSmsCode,
			@RequestParam(value="newMobile",required=true)@ApiParam(value="新的电话号码",required=true)String newMobile,
			@RequestParam(value="newSmsCode",required=true)@ApiParam(value="新的短信验证码",required=true)String newSmsCode){
		if (StringUtils.isAnyBlank(oldMobile,oldSmsCode)) {
			return GenericResponse.ng("旧的手机号、旧的短信验证码都不能为空");
		}
		
		boolean isVerified = verificationCodeService.verifyVerificationCode(oldMobile, oldSmsCode);
		if (!isVerified) {
			return GenericResponse.ng("旧的短信验证码不正确或已超时");
		}
		
		if (StringUtils.isAnyBlank(newMobile,newSmsCode)) {
			return GenericResponse.ng("新的手机号、新的短信验证码都不能为空");
		}
		
		boolean isVerified2 = verificationCodeService.verifyVerificationCode(oldMobile, oldSmsCode);
		if (!isVerified2) {
			return GenericResponse.ng("新的短信验证码不正确或已超时");
		}
		MerchantMgrEntity merchant = merchantMgrRep.findByMobile(oldMobile);
		
		MerchantMgrEntity newMerchant = merchantMgrRep.findByMobile(newMobile);
		if(newMerchant==null){
			merchant.setMobile(newMobile);
			merchantMgrRep.save(merchant);
			return GenericResponse.ok();
		}else{
			return GenericResponse.ng("新手机号已经注册过不能重新绑定！");
		}
		
		
	}
	@ApiOperation(value = "验证邮箱是否存在(0000不存在9999存在)", notes = "邮验证邮箱是否存在")
	@ApiResponses({ @ApiResponse(code = 200, message = "验证邮箱是否存在", response = ManagerAccountDataResponse.class)})
	@RequestMapping(value = "/isMail", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> existEmail(@RequestParam(value="email",required=true)String email) {
		MerchantMgrEntity merchantMgr = managerAccountSer.findByEmail(email);
		if(merchantMgr!=null){
			return GenericResponse.ng("邮箱已经存在");
		}
		return GenericResponse.ok();
		
	}

	@ApiOperation(value = "邮箱注册", notes = "邮箱注册")
	@ApiResponses({ @ApiResponse(code = 200, message = "邮箱注册", response = ManagerAccountDataResponse.class) })
	@RequestMapping(value = "/reg_by_mail", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> registerByEmail(@RequestBody MailVo mailVo) {
		String mobile = mailVo.getMobile();
		String passwd = mailVo.getPasswd();
		String email = mailVo.getEmail();
		MerchantMgrEntity merchantMgrInDB;
		String smsCode = mailVo.getSmsCode();
		if (StringUtils.isEmpty(mobile)) {
			return GenericResponse.ng("手机号不能为空！");
		}
		if (StringUtils.isEmpty(passwd)) {
			return GenericResponse.ng("密码不能为空！");
		}
		if (StringUtils.isEmpty(email)) {
			return GenericResponse.ng("邮箱不能为空！");
		}
		if (StringUtils.isEmpty(smsCode)) {
			return GenericResponse.ng("手机验证码不能为空！");
		}
		
		boolean isVerified = verificationCodeService.verifyVerificationCode(mobile, smsCode);
		if (!isVerified) {
			return GenericResponse.ng("短信验证码不正确或已超时");
		}
		MerchantMgrEntity merchantMgr = new MerchantMgrEntity();
		BeanUtils.copyProperties(mailVo, merchantMgr);
		String id = idGenerator.nextId();
		merchantMgr.setId(id);
		merchantMgr.setName(idGenerator.nextId());
		merchantMgr.setStep(1);
		merchantMgr.setRoleId("superManager001");
		try {
			merchantMgrInDB = managerAccountSer.createByEmail(merchantMgr);
		} catch (Exception e) {
			return GenericResponse.ng(e.getMessage());
		}

		Integer durToken = mailVo.getDurToken();
		HttpHeaders httpHeaders = null;
		if (durToken != null && durToken != 0) {
			httpHeaders = setToken4HttpHeadersByDays(merchantMgrInDB.getId(), durToken);
		} else {
			httpHeaders = setToken4HttpHeaders(String.valueOf(merchantMgrInDB.getId()));
		}

		ManagerAccountVo managerAccountVo = new ManagerAccountVo();
		BeanUtils.copyProperties(merchantMgrInDB, managerAccountVo);
		String merchantId = merchantMgrInDB.getMerchantId();
		String merchantStatus = merchantDubboApi.getMerchantStatus(merchantId);
		if (StringUtils.isEmpty(merchantStatus)) {
			merchantStatus = "00";
		}
		managerAccountVo.setMerchantStatus(merchantStatus);
		return ManagerAccountDataResponse.okWithData(managerAccountVo, httpHeaders);

	}
	
	@ApiOperation(value = "管理员手机号注册", notes = "管理员手机号注册")
	@ApiResponses({ @ApiResponse(code = 200, message = "注册结果", responseHeaders = {
			@ResponseHeader(name = "access_token", response = String.class),
			@ResponseHeader(name = "refresh_token", response = String.class)}, response = ManagerAccountDataResponse.class),
		@ApiResponse(code=400, message="手机号、密码、验证码都不能为空"),
		@ApiResponse(code=403, message="短信验证码不正确或已超时"),
		@ApiResponse(code=409, message="手机号已经存在")})
	@RequestMapping(value = "/reg_by_mobile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> registerByCellphoneNumber(@RequestBody LoginVo loginVo) {
		String mobile = loginVo.getMobile();
		String passwd = loginVo.getPasswd();
		String smsCode = loginVo.getSmsCode();
		MerchantMgrEntity merchantMgrInDB;
		if (StringUtils.isAnyBlank(mobile, passwd)) {
			return GenericResponse.ng("手机号、密码都不能为空");
		}
		boolean isVerified = verificationCodeService.verifyVerificationCode(mobile, smsCode);
//		if (!isVerified) {
//			return GenericResponse.ng("短信验证码不正确或已超时");
//		}
		try {
			MerchantMgrEntity merchantMgr = new MerchantMgrEntity();
			BeanUtils.copyProperties(loginVo, merchantMgr);
			String id = idGenerator.nextId();
			merchantMgr.setId(id);
			merchantMgr.setName(idGenerator.nextId());
			merchantMgr.setStep(1);
			merchantMgr.setRoleId("superManager001");
			merchantMgrInDB = managerAccountSer.createByCellphoneNumber(merchantMgr);
		} catch (Exception uae) {
			return GenericResponse.ng("手机号已经存在！");
		}

		Integer durToken = loginVo.getDurToken();
		HttpHeaders httpHeaders = null;
		if (durToken != null && durToken != 0) {
			httpHeaders = setToken4HttpHeadersByDays(merchantMgrInDB.getId(), durToken);
		} else {
			httpHeaders = setToken4HttpHeaders(String.valueOf(merchantMgrInDB.getId()));
		}

		ManagerAccountVo managerAccountVo = new ManagerAccountVo();
		BeanUtils.copyProperties(merchantMgrInDB, managerAccountVo);
		String merchantId = merchantMgrInDB.getMerchantId();
		String merchantStatus = merchantDubboApi.getMerchantStatus(merchantId);
		if (StringUtils.isEmpty(merchantStatus)) {
			merchantStatus = "00";
		}
		managerAccountVo.setMerchantStatus(merchantStatus);
		return ManagerAccountDataResponse.okWithData(managerAccountVo, httpHeaders);

	}
	@ApiOperation(value = "管理员邮箱密码登录（根据正则表达式来选用调用接口）", notes = "管理员邮箱密码登录")
	@ApiResponses({ @ApiResponse(code = 200, message = "管理员邮箱密码登录", response = ManagerAccountDataResponse.class)})
	@RequestMapping(value = "/login_by_email", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> loginByEmail(@RequestBody MailVo mailVo) {
		if (StringUtils.isAnyBlank(mailVo.getEmail(), mailVo.getPasswd())) {
			return GenericResponse.ng("手机号密码都不能为空！");
		}
		MerchantMgrEntity merchantMgrInDB;
		try {
			merchantMgrInDB = managerAccountSer.loginByEmail(mailVo.getMobile(), mailVo.getPasswd(), mailVo.getTermDevice());
		} catch (Exception ex) {
			return GenericResponse.ng(ex.getMessage());
		}
		Integer durToken = mailVo.getDurToken();
		HttpHeaders httpHeaders = null;
		if(durToken!=null&&durToken!=0){
			httpHeaders = setToken4HttpHeadersByDays(merchantMgrInDB.getId(),durToken);
		}else{
			httpHeaders = setToken4HttpHeaders(String.valueOf(merchantMgrInDB.getId()));
		}
		
		String merchantId = merchantMgrInDB.getMerchantId();
		String merchantStatus = merchantDubboApi.getMerchantStatus(merchantId);
		if(StringUtils.isEmpty(merchantStatus)){
			merchantStatus = "00";
		}
		ManagerAccountVo managerAccountVo = new ManagerAccountVo();
		BeanUtils.copyProperties(merchantMgrInDB, managerAccountVo);
//		if("200".equals(merchantStatus)){
		//TODO 这里需要打开
		if (true) {
			String roleId = merchantMgrInDB.getRoleId();
			MerchantRoleEntity merchantRole = merchantRoleSer.findById(roleId);
			List<MerchantFunInner> merchantFunList = merchantRole.getRoleList();
			managerAccountVo.setMenuList(merchantFunList);
		}
		String shopId = managerAccountVo.getShopId();
		SitesInfo4SocialVo sitesInfo = sitesApi.getSiteInfo4Social(shopId);
		String shopName = "";
		if(sitesInfo!=null){
			shopName = sitesInfo.getName();
		}
		managerAccountVo.setMerchantStatus(merchantStatus);
		managerAccountVo.setShopName(shopName);
		return ManagerAccountDataResponse.okWithData(managerAccountVo, httpHeaders);
		
	}
	@ApiOperation(value = "管理员手机号+密码登录", notes = "管理员手机号+密码登录")
	@ApiResponses({ @ApiResponse(code = 200, message = "登录结果", responseHeaders = {
			@ResponseHeader(name = "access_token", response = String.class),
			@ResponseHeader(name = "refresh_token", response = String.class) },response = ManagerAccountDataResponse.class),
		@ApiResponse(code=400, message="手机号、密码、验证码都不能为空"),
		@ApiResponse(code=401, message="手机号或密码错误"),
		@ApiResponse(code=403, message="验证码不正确或已超时")})
	@RequestMapping(value = "/login_by_passwd", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
	public ResponseEntity<?> loginByCellphoneNumberAndPassword(@RequestBody LoginVo loginVo) {

		if (StringUtils.isAnyBlank(loginVo.getMobile(), loginVo.getPasswd())) {
			return GenericResponse.ng("手机号、密码都不能为空");
		}

		String mobile = loginVo.getMobile();

		boolean result = isMobileNO(mobile);
		if(result){
			// 1、执行登录
			MerchantMgrEntity merchantMgrInDB;
			try {
				merchantMgrInDB = managerAccountSer.loginByMobileAndPasswd(loginVo.getMobile(), loginVo.getPasswd(), loginVo.getTermDevice());
			} catch (AuthenFailException ex) {
				return GenericResponse.ng("手机号或密码错误");
			}
			Integer durToken = loginVo.getDurToken();
			HttpHeaders httpHeaders = null;
			if(durToken!=null&&durToken!=0){
				httpHeaders = setToken4HttpHeadersByDays(merchantMgrInDB.getId(),durToken);
			}else{
				httpHeaders = setToken4HttpHeaders(String.valueOf(merchantMgrInDB.getId()));
			}
			String merchantId = merchantMgrInDB.getMerchantId();
			String merchantStatus = merchantDubboApi.getMerchantStatus(merchantId);
			if(StringUtils.isEmpty(merchantStatus)){
				merchantStatus = "00";  //状态  00未认证, 10 待审核 , 20审核成功, 30 审核失败
			}
			ManagerAccountVo managerAccountVo = new ManagerAccountVo();
			BeanUtils.copyProperties(merchantMgrInDB, managerAccountVo);
			if ("20".equals(merchantStatus)) {
				String roleId = merchantMgrInDB.getRoleId();
				MerchantRoleEntity merchantRole = merchantRoleSer.findById(roleId);
				List<MerchantFunInner> merchantFunList = merchantRole.getRoleList();
				managerAccountVo.setMenuList(merchantFunList);

			}
//		else{
//			return GenericResponse.ng("资质没有审核通过！");
//		}
			String shopId = managerAccountVo.getShopId();
			SitesInfo4SocialVo sitesInfo = sitesApi.getSiteInfo4Social(shopId);
//		SitesInfo4SocialVo sitesInfo = null;
			String shopName = "";
			if(sitesInfo!=null){
				shopName = sitesInfo.getName();
				managerAccountVo.setLogo(sitesInfo.getLogo());
			}
			managerAccountVo.setMerchantStatus(merchantStatus);
			managerAccountVo.setShopName(shopName);
			managerAccountVo.setMerchantStatus(merchantStatus);
			return ManagerAccountDataResponse.okWithData(managerAccountVo, httpHeaders);

		}else{

			MerchantMgrEntity merchantMgrInDB;
			try {
				merchantMgrInDB = managerAccountSer.loginByMobileAndPasswd(loginVo.getMobile(), loginVo.getPasswd(), loginVo.getTermDevice());

			}catch (AuthenFailException ex) {
				return GenericResponse.ng("手机号或密码错误");
			}
			Integer durToken = loginVo.getDurToken();
			HttpHeaders httpHeaders = null;
			if(durToken!=null&&durToken!=0){
				httpHeaders = setToken4HttpHeadersByDays(merchantMgrInDB.getId(),durToken);
			}else{
				httpHeaders = setToken4HttpHeaders(String.valueOf(merchantMgrInDB.getId()));
			}
			ManagerAccountVo managerAccountVo = new ManagerAccountVo();
			BeanUtils.copyProperties(merchantMgrInDB, managerAccountVo);
			String roleId = merchantMgrInDB.getRoleId();
			MerchantRoleEntity merchantRole = merchantRoleSer.findById(roleId);
			List<MerchantFunInner> merchantFunList = merchantRole.getRoleList();
			managerAccountVo.setMenuList(merchantFunList);
			return ManagerAccountDataResponse.okWithData(managerAccountVo, httpHeaders);

		}
		


	}


	public boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	
	
	@ApiOperation(value = "对应景区的角色列表", notes = "对应景区的角色列表")
	@ApiResponses({ @ApiResponse(code = 200, response = MerchantRoleListResponse.class, message = "对应景区的角色列表") })
	@GetMapping(value = "/roles", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> role2FunList(HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<MerchantRoleEntity> merchantRoles= merchantRoleSer.findMerchantRoleBySitesId(shopId);
		List<MerchantRoleVo> merchantRoleVoList = new ArrayList<>();
		MerchantRoleVo merchantRoleVo = null;
		for(MerchantRoleEntity merchantRole:merchantRoles){
			merchantRoleVo = new MerchantRoleVo();
			BeanUtils.copyProperties(merchantRole, merchantRoleVo);
			String id = merchantRoleVo.getId();
			List<MerchantMgrEntity> merchantMgrList = merchantMgrRep.findByRoleId(id,shopId);
			if(merchantMgrList!=null){
				merchantRoleVo.setManagerNum(merchantMgrList.size());
			}
			merchantRoleVoList.add(merchantRoleVo);
		}
		return MerchantRoleListResponse.listNoCount(merchantRoleVoList);
	}
	
	@ApiOperation(value = "删除一个角色", notes = "删除一个角色")
	@ApiResponses({ @ApiResponse(code = 200, response = MerchantRoleDataResonse.class, message = "删除一个角色") })
	@DeleteMapping(value = "/roles", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> deleteRole(@RequestParam(value="roleId",required=true)@ApiParam(value="角色Id",required = true)String roleId,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<MerchantMgrEntity> merchantMgrList = merchantMgrRep.findByRoleId(roleId,shopId);
		if(CollectionUtils.isEmpty(merchantMgrList)){
			MerchantMgrEntity merchantMgr = new MerchantMgrEntity();
			merchantMgr.setRoleId(roleId);
			boolean isSuperManager = isSuperManager(merchantMgr);
			if(isSuperManager){
				return GenericResponse.ng("你没有权限删除超级管理员权限");
			}else{
				boolean result = merchantRoleSer.deleteMerchantRole(roleId);
				if(result){
					return GenericResponse.ok();
				}else{
					return GenericResponse.ng("删除失败！");
				}
			}
		}else{
			return GenericResponse.ng("请删除角色下的管理员在删除此角色！");
		}

	}
	
	@ApiOperation(value = "为景区添加一个角色", notes = "为景区添加一个角色")
	@ApiResponses({ @ApiResponse(code = 200, response = MerchantRoleDataResonse.class, message = "为景区添加一个角色") })
	@PostMapping(value = "/roles", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addRole(@RequestBody MerchantRoleVo merchantRoleVo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		MerchantRoleEntity merchantRoleInDB = null;
		MerchantRoleEntity merchantRole = new MerchantRoleEntity();
		BeanUtils.copyProperties(merchantRoleVo, merchantRole);
		merchantRole.setId(idGenerator.nextId());
		merchantRole.setCode("100");
		merchantRole.setSitesId(shopId);
		merchantRoleInDB = merchantRoleSer.add(merchantRole);
		return MerchantRoleDataResonse.okWithData(merchantRoleInDB);
	}
	@ApiOperation(value = "修改角色（注意一旦角色改变所有拥有这些角色的管理员权限会改变）", notes = "修改角色(谨慎修改)")
	@ApiResponses({ @ApiResponse(code = 200, response = MerchantRoleDataResonse.class, message = "修改角色") })
	@PutMapping(value = "/roles", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateRole(@RequestBody MerchantRoleVo merchantRoleVo,HttpServletRequest request) {
		String id = merchantRoleVo.getId();
		MerchantRoleEntity merchantRoleInDB = null;
		merchantRoleInDB = merchantRoleSer.findById(id);
		if(merchantRoleInDB==null){
			return GenericResponse.ng("不存在这种角色！");
		}else{
			MerchantRoleEntity merchantRole = new MerchantRoleEntity();
			BeanUtils.copyProperties(merchantRoleVo, merchantRole);
			merchantRoleInDB = merchantRoleSer.add(merchantRole);
		}
		return MerchantRoleDataResonse.okWithData(merchantRoleInDB);
	}
	
	@ApiOperation(value = "账号设置", notes = "账号设置")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "账号设置") })
	@PostMapping(value = "/{userId}/account", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateMgr(
			@PathVariable(value = "userId", required = false) @ApiParam(value = "userId", required = false) String userId,
			@RequestBody ManagerUpdateVo managerUpdateVo) {

		String mobile = managerUpdateVo.getMobile();
		String oldPwd = managerUpdateVo.getOldPwd();
		String newPwd = managerUpdateVo.getNewPwd();
		String name = managerUpdateVo.getName();
		String logoUrl = managerUpdateVo.getLogoUrl();
		try {
			boolean result = managerAccountSer.updateMgr(mobile, oldPwd, newPwd, name, logoUrl);
			if (result) {
				return GenericResponse.ok();
			}
		} catch (Exception e) {
			String msg = e.getMessage();
			LOG.error(msg);
			return GenericResponse.ng(msg);
		}

		return GenericResponse.ng("添加失败！");

	}
	
	@ApiOperation(value = "获取管理员信息", notes = "获取管理员信息")
	@ApiResponses({ @ApiResponse(code = 200, response = ManagerDataResponse.class, message = "获取管理员信息") })
	@GetMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> merchantMgrDetail(HttpServletRequest request) {
		String managerId = (String) request.getAttribute("userId");
		MerchantMgrEntity merchantMgr = managerAccountSer.findById(managerId);
		ManagerVo managerVo = new ManagerVo();
		if(merchantMgr!=null){
			BeanUtils.copyProperties(merchantMgr, managerVo);
		}
		return ManagerDataResponse.okWithData(managerVo);
		
	}
	
	@ApiOperation(value = "添加员工(通过roleId给员工授权)", notes = "添加员工")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "添加员工") })
	@PostMapping(value = "/{userId}/man_mgr", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addManager(
			@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId,
			@RequestBody ManagerAdditionVo managerAdditionVo) {
		MerchantMgrEntity merchantInDB = managerAccountSer.findById(userId);
		MerchantMgrEntity merchantMgr = new MerchantMgrEntity();
		if(merchantInDB!=null){
			if(isSuperManager(merchantInDB)){
				BeanUtils.copyProperties(managerAdditionVo, merchantMgr);
				String shopId = merchantInDB.getShopId();
				String shopType = merchantInDB.getShopType();
				String merchantId = merchantInDB.getMerchantId();
				String managerId = idGenerator.nextId();
				merchantMgr.setId(managerId);
				merchantMgr.setShopId(shopId);
				merchantMgr.setShopType(shopType);
				merchantMgr.setMerchantId(merchantId);
				merchantMgr.setStep(4);
				try {
					MerchantMgrEntity merchantMgrResult = managerAccountSer.addMerchantMgr(merchantMgr);
					if(merchantMgrResult!=null){
						return GenericListResponse.ok();
					}
				} catch (Exception e) {
					String erroMsg = e.getMessage();
					LOG.error(erroMsg, e);
					return GenericResponse.ng(erroMsg);
				}
				
			}
			
		}else{
			return GenericResponse.ng("您不是超级管理员没有权限进行此项操作！");
		}
		return GenericResponse.ng("添加失败！");

	}
	
	private HttpHeaders setToken4HttpHeaders(String userId) {
		// 为用户生成access_token与refresh_token,手机端进行缓存,进入信息完善页面时,可以利用access_token与refresh_token进行用户信息更新
		OAuth2TokenEntity oAuth2Token = oAuth2Service.getAccessTokenAndRefreshToken4XiaoqAPP(userId,
				"lifestyle365-secret-201611120-20221119", 365);
		String bearerAccessToken = "Bearer " + oAuth2Token.getAccessToken();
		String refreshToken = oAuth2Token.getRefreshToken();

		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.set("access_token", bearerAccessToken);
		httpHeaders.set("refresh_token", refreshToken);
		return httpHeaders;
	}
	
	
	private HttpHeaders setToken4HttpHeadersByDays(String userId,int durToken) {
		// 为用户生成access_token与refresh_token,手机端进行缓存,进入信息完善页面时,可以利用access_token与refresh_token进行用户信息更新
		OAuth2TokenEntity oAuth2Token = oAuth2Service.getAccessTokenAndRefreshToken4XiaoqAPP(userId,
				"lifestyle365-secret-201611120-20221119", durToken);
		String bearerAccessToken = "Bearer " + oAuth2Token.getAccessToken();
		String refreshToken = oAuth2Token.getRefreshToken();

		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.set("access_token", bearerAccessToken);
		httpHeaders.set("refresh_token", refreshToken);
		return httpHeaders;
	}
	
	/**
	 * 判断一个管理员是不是管理员
	 * @param merchantMgr
	 * @return
	 */
	private boolean isSuperManager(MerchantMgrEntity merchantMgr){
		String roleId = merchantMgr.getRoleId();
		MerchantRoleEntity merchantRole = merchantRoleSer.findById(roleId);
		if(merchantRole!=null){
			String code = merchantRole.getCode();
			if("000".equals(code)){
				return true;
			}
		}
		return false;
		
	}
	
	
}
